var opn = require('opn')
var path = require('path')
var http = require('http')
var fs = require('fs')
var $ = require('./util.js')
var express = require('express')
var color = require('colors')
var bodyParser = require('body-parser')
const WebSocket = require('ws')

// 判断config.json是否存在，不存在则创建config.json
var config = ''
if (fs.existsSync('./server/config.json')) {
  config = JSON.parse(fs.readFileSync('./server/config.json', 'utf-8'))
} else {
  $.copyFileSync('./server/_config.json', './server/config.json')
  config = JSON.parse(fs.readFileSync('./server/_config.json', 'utf-8'))
}

var port = config.api_port
var routes = require('./router')
var autoSign = require('./sign')


// 检查index.html 和 login.html 是否存在
// 根据config.json中的app，替换上述两个文件中mate中的APP_CODE
fs.exists("./index.html", function(exists) {
    if (!exists) {
      $.copyFileSync('./_index.html', './index.html')
    }
    $.changeAppCode('./index.html', config.app)
});
fs.exists("./login.html", function(exists) {
    if (!exists) {
      $.copyFileSync('./_login.html', './login.html')
    }
    $.changeAppCode('./login.html', config.app)
});


var app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false
}))
app.use(autoSign)
app.use('/', routes)

var uri = 'http://localhost:' + port

var _resolve
var readyPromise = new Promise(resolve => {
  _resolve = resolve
})
console.log('> Starting api server...')
const server = http.createServer(app)
const wss = new WebSocket.Server({ server})
wss.on('connection', function connection (ws, req) {
  ws.on('message', function incoming (message) {
    console.log('received: %s', message)
  })
  /*
  setInterval(() => {
    var data = {
      id: 10,
      title: '数据导入完成'
    }
    ws.send(JSON.stringify(data))
  }, 2000)
  */
  ws.send('something')
})

server.listen(8081)
module.exports = {
  ready: readyPromise,
  close: () => {
    server.close()
  }
}
